package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.ServletUtils;
import com.spzx.product.domain.ProductSpec;
import com.spzx.product.mapper.ProductSpecMapper;
import com.spzx.product.service.CategoryService;
import com.spzx.product.service.ProductSpecService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements ProductSpecService {

    @Resource
    CategoryService categoryService;

    @Override
    public ProductSpec selectSpecById(Long id) {
        ProductSpec spec = this.getById(id);
        if (spec != null) {
            spec.setCategoryIdList(categoryService.selectCategoryIdsByC3Id(spec.getCategoryId()));
        }
        return spec;
    }

    @Override
    public Page<ProductSpec> listProductSpec(ProductSpec productSpec) {
        Integer pageNum = ServletUtils.getParameterToInt("pageNum", 1);
        Integer pageSize = ServletUtils.getParameterToInt("pageSize", 3);

        Page<ProductSpec> page = new Page<>(pageNum, pageSize);
        if (page != null) {

            List<ProductSpec> list = baseMapper.selectProductSpecPage(page, productSpec);
            page.setRecords(list);
            return page;

        }

        return null;
    }

    @Override
    public boolean checkSpecIsUnique(ProductSpec productSpec) {
        // 判断是新增 还是 更新
        Long id = productSpec.getId() == null ? -1L : productSpec.getId();
        String specName = productSpec.getSpecName();
        Long categoryId = productSpec.getCategoryId();
        ProductSpec selectSpec = this.getOne(Wrappers.lambdaQuery(ProductSpec.class).eq(ProductSpec::getSpecName, specName)
                .eq(ProductSpec::getCategoryId, categoryId).last("limit 1"));
                // 如果 selectSpec 等于空  新增  如果新增和更新 selectSpec 都不等空 比较id 是否存在
                // 有id 更新 无id 新增
        if (selectSpec != null && id.longValue() != selectSpec.getId().longValue()) {
            return false;
        }
        return true;
    }
}
